<template>
  <view class="service-ticket-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="咨询留言列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="search-bar">
            <view class="search-bar-item" @click="showDateTimePickerModal">
              <text class="title">留言日期</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="search-bar-item" @click="showPicker1 = true">
              <text class="title">是否本人</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <up-picker :show="showPicker1" :columns="columns1" :closeOnClickOverlay="true" @confirm="handleIsOwnConfirm"
              @cancel="showPicker1 = false" @close="showPicker1 = false"></up-picker>
          </view>

          <up-search v-model="formData.keyword" :clearabled="true" :showAction="false" placeholder="请输入手机号/留言内容"
            @search="handleSearch" @clear="handleClear"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="service-ticket-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              咨询留言ID：<text class="number">{{ item.bizCode }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag :text="getDealStatusText(item.dealStatus)" :type="getDealStatusType(item.dealStatus)">
                    </up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  车主姓名：
                </text>
                <text class="value">
                  {{ item.userName || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  车主电话：
                </text>
                <text class="value">
                  {{ item.userPhone || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  订单号：
                </text>
                <text class="value">
                  {{ item.orderNo || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  咨询内容：
                </text>
                <text class="value content-text">
                  {{ item.content || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  提交时间：
                </text>
                <text class="value">
                  {{ item.createTime || '-' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  咨询次数：
                </text>
                <text class="value">
                  {{ item.submitNum || 0 }}
                </text>
              </view>
              <view class="item" v-if="item.dealStatus !== 0">
                <text class="label">
                  处理人员：
                </text>
                <text class="value">
                  {{ item.dealUserName || '-' }}
                </text>
              </view>
              <view class="item" v-if="item.dealStatus !== 0">
                <text class="label">
                  处理时间：
                </text>
                <text class="value">
                  {{ item.dealTime || '-' }}
                </text>
              </view>
              <view class="item" v-if="item.dealRemark">
                <text class="label">
                  处理备注：
                </text>
                <text class="value content-text">
                  {{ item.dealRemark }}
                </text>
              </view>
            </view>
            <view class="card-footer" v-if="item.dealStatus === 0">
              <view class="operate">
                <up-button type="primary" text="处理留言" plain class="custom-style" @click="handleReply(item)"></up-button>
                <up-button type="warning" text="挂起留言" plain class="custom-style" @click="handleWait(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <OrderAppealModal v-model:show="show" :type="type" :row-data="editingData" />
    <up-datetime-picker closeOnClickOverlay :show="showDateTimePicker" v-model="formData.messageDate" mode="date"
      @cancel="hideDateTimePickerModal" @confirm="handleDateConfirm"
      @close="hideDateTimePickerModal"></up-datetime-picker>

    <!-- 回复留言弹窗 -->
    <up-modal :show="showReplyModal" title="处理留言" @confirm="handleReplyConfirm" @cancel="showReplyModal = false" @close="showReplyModal = false"
      :closeOnClickOverlay="true">
      <view class="reply-content" style="width: 100%;">
        <up-textarea v-model="replyText" placeholder="请输入回复内容" :maxlength="200" style="width: 100%;" />
      </view>
    </up-modal>
    
    <!-- 挂起留言弹窗 -->
    <up-modal :show="showWaitModal" title="挂起留言" @confirm="handleWaitConfirm" @cancel="showWaitModal = false" @close="showWaitModal = false"
      :closeOnClickOverlay="true">
      <view class="wait-content" style="width: 100%; padding: 10px;">
        <text>请输入挂起原因：</text>
        <up-textarea
          v-model="waitText"
          placeholder="请输入挂起原因"
          style="width: 100%; margin-top: 10px;"
        ></up-textarea>
      </view>
    </up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { getFeedbackList, dealFeedback, suspendFeedback } from '@/api';
import OrderAppealModal from './components/OrderAppealModal.vue'
import { formatTime } from '@/utils/tools';

const { bool: show, setTrue: openModal } = useBoolean();
const { bool: showDateTimePicker, setTrue: showDateTimePickerModal, setFalse: hideDateTimePickerModal } = useBoolean();
const type = ref('add')
const editingData = ref({})
const formData = reactive({
  messageDate: Date.now(),
  isSelf: -1, // -1.全部 0.全部 1.本人
  keyword: '', // 内容关键字查询
})

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待处理' },
  { name: '已处理' },
  { name: '已挂起' },
];
const currentTab = ref(0);
const showPicker1 = ref(false);

const columns1 = reactive([['全部', '本人']]);
// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理留言
// 回复弹窗相关变量
const showReplyModal = ref(false);
const replyText = ref('');
const currentItem = ref<any>(null);

// 打开回复弹窗
const handleReply = (item: any) => {
  currentItem.value = item;
  replyText.value = '';
  showReplyModal.value = true;
}

// 确认回复
const handleReplyConfirm = async () => {
  if (!replyText.value.trim()) {
    uni.showToast({
      title: '回复内容不能为空',
      icon: 'none'
    });
    return;
  }

  try {
    // 调用处理留言接口
    const res = await dealFeedback({
      bizCode: currentItem.value.bizCode,
      dealRemark: replyText.value.trim()
    });

    // 判断返回结果的success字段
    if (res.success) {
      uni.showToast({
        title: '处理成功',
        icon: 'success'
      });

      // 关闭弹窗
      showReplyModal.value = false;

      // 刷新列表
      paging.value.reload();
    } else {
      // 显示返回的错误信息
      uni.showToast({
        title: res.msg || '处理失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('处理留言失败:', error);
    uni.showToast({
      title: '处理失败，请重试',
      icon: 'none'
    });
  }
}

// 挂起留言相关变量
const showWaitModal = ref(false);
const waitText = ref('');

// 打开挂起留言弹窗
const handleWait = (item: any) => {
  currentItem.value = item;
  waitText.value = '';
  showWaitModal.value = true;
}

// 确认挂起留言
const handleWaitConfirm = async () => {
  if (!waitText.value.trim()) {
    uni.showToast({
      title: '挂起原因不能为空',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 调用挂起留言接口
    const res = await suspendFeedback({
      bizCode: currentItem.value.bizCode,
      dealRemark: waitText.value.trim()
    });
    
    // 判断返回结果的success字段
    if (res.success) {
      uni.showToast({
        title: '挂起成功',
        icon: 'success'
      });
      
      // 关闭弹窗
      showWaitModal.value = false;
      
      // 刷新列表
      paging.value.reload();
    } else {
      // 显示返回的错误信息
      uni.showToast({
        title: res.msg || '挂起失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('挂起留言失败:', error);
    uni.showToast({
      title: '挂起失败，请重试',
      icon: 'none'
    });
  }
}

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}


// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 根据当前选项卡设置处理状态
    let dealStatus = -1; // 默认全部
    if (currentTab.value === 1) {
      dealStatus = 0; // 待处理
    } else if (currentTab.value === 2) {
      dealStatus = 1; // 已处理
    } else if (currentTab.value === 3) {
      dealStatus = 2; // 挂起
    }

    // 格式化日期
    const searchDate = formData.messageDate ? formatTime(formData.messageDate, 'YYYY-MM-DD') : '';

    const requestParams = {
      dealStatus,
      searchDate,
      isOwn: formData.isSelf,
      keyword: formData.keyword,
      pageNum: params.pageNum,
      pageSize: params.pageSize
    };

    const result: any = await getFeedbackList(requestParams);
    const data = result.data;
    paging.value.complete(data.records || []);
  } catch (error) {
    console.error('获取咨询留言列表失败:', error);
    paging.value.complete(false);
  }
}


// 处理是否本人选择器确认
const handleIsOwnConfirm = (e) => {
  const selectedIndex = e.indexs[0];
  formData.isSelf = selectedIndex === 0 ? -1 : 1; // 0为全部(-1)，1为本人(1)
  showPicker1.value = false;

  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理日期选择器确认
const handleDateConfirm = (e) => {
  // 关闭日期选择器
  hideDateTimePickerModal();

  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  formData.keyword = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 获取处理状态文本
const getDealStatusText = (status) => {
  switch (status) {
    case 0:
      return '待处理';
    case 1:
      return '已处理';
    case 2:
      return '挂起';
    default:
      return '未知';
  }
};

// 获取处理状态类型
const getDealStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'success';
    case 2:
      return 'info';
    default:
      return 'default';
  }
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.service-ticket-list {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 30rpx;

  &-item {
    display: flex;
    flex: 1;
    justify-content: center;
    align-items: center;
    text-align: center;

    .item-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-text {
  word-break: break-all;
  white-space: pre-wrap;
  max-width: 400rpx;
}
</style>